package com.calvin.study.lock.deadlock;

import java.io.Serializable;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

//线程死锁
public class DeadLockDemo {

	public static void main(String[] args) {
		new Thread(new HoldThread("lockA", "lockB"), "Thread_A").start();
		new Thread(new HoldThread("lockB", "lockA"), "Thread_B").start();

		// order1属于引用，在栈中，栈的引用指向了堆的内存
		Order order1 = new Order();
		Order order2 = new Order();
		// 而创建出来的实例，是不同的实例对象（内存地址不同），如何确保他们拥有同样的行为？
		// order1 order2是属于同一个Order模板
	}

}

//资源类
class HoldThread implements Runnable {

	private String lockA;
	private String lockB;

	public HoldThread(String lockA, String lockB) {
		this.lockA = lockA;
		this.lockB = lockB;
	}

	@Override
	public void run() {
		synchronized (lockA) {
			System.out.println(Thread.currentThread().getName() + "\t 自己持有锁" + lockA + "尝试获得\t" + lockB);

			synchronized (lockB) {
				System.out.println(Thread.currentThread().getName() + "\t 自己持有锁" + lockB + "尝试获得" + lockA);
			}
		}
	}

}

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
class Order implements Serializable {

	private static final long serialVersionUID = 6523460473927227344L;

	private String orderId;

	private String orderName;

}
